<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Goods;
use App\User;
use DB;

class CartController extends Controller
{
    /**
     * 添加商品到购物车
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function insert(Request $request)
    {
        $user = User::findorFail(session('id'));
        $goods = Goods::findorFail($request->id);

        // 检测
        if($this->checkExists($request->id)) {
            $this->increNum($request->id, $request->num);
            return redirect('/home/cart/index');
        }
        
        $user->cart_goods()->save($goods,[
            'number'=>$request->num,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
            ]);
    }
     private function checkExists($id)
    {
        return DB::table('carts')->where('goods_id',$id)->where('user_id',session('id'))->first() ? true : false;
    }

    private function increNum($id, $num)
    {
        $res = DB::table('carts')->where('goods_id',$id)->where('user_id',session('id'))->first();

        $number = $res->number + $num;

        return DB::table('carts')->where('goods_id',$id)->where('user_id', session('id'))->update(['number'=>$number]);
    }

    public function index()
    {
        //读取用户的购物车信息
        $user = User::find(session('id'));

        $goods = $user->cart_goods;
        return view('home.cart.index',['goods'=>$goods]);
    }


    /**
     * 执行前台购物车删除商品操作
     */
    // public function delete($id)
    // {
    //     dd(222);
    //     //获取数据
    //     $cart = cart::findOrFail($id);
    //     //删除子分类
    //     if($cart->delete()){
    //         return back()->with('success','执行成功');
    //     }else{
    //         return back()->with('error','执行失败');
    //     }
        
    // }
}
